let urls = {
    "US": "https://www.amazon.com/dp/",
    "UK": "https://www.amazon.co.uk/dp/",
    "CA": "https://www.amazon.ca/dp/",
    "DE": "https://www.amazon.de/dp/",
    "FR": "https://www.amazon.fr/dp/",
    "MX": "https://www.amazon.com.mx/dp/",
    "JP": "https://www.amazon.co.jp/dp/"
  };

function isValidASIN(asin) {
    // ASIN 是由10个字母或数字组成的字符串
    const asinRegex = /^[A-Z0-9]{10}$/;
    return asinRegex.test(asin);
}

function openBrowser(url){
    let linkCell = Application.ActiveSheet.Range('ZZ99999')
    let link=window.Application.ActiveSheet.Hyperlinks.Add(linkCell, url);//创建超链接
    // 执行超链接
    link.Follow();
    link.Delete();
    linkCell.Delete();
}

function getCopySelection(){
    // 获取选中后复制到剪贴版的内容
    // 无法直接获取鼠标选中的内容，可以先将复制的内容写入range
    let linkCell = Application.ActiveSheet.Range('ZZ99999')
    window.Application.ActiveSheet.Paste(linkCell)
    let copyData = linkCell.Value2
    linkCell.Delete()
    // 将剪贴板的内容置空
    Application.ActiveSheet.Range('ZZ99999').Copy()
    return copyData
}

function onOpenAmazon() {
    
    let select_site = window.Application.PluginStorage.getItem("select_site")
    let browser_type = window.Application.PluginStorage.getItem("browser_type")

    let asin = ''
    // 当前活动单元格内的内容
    let ActiveCell = window.Application.ActiveCell.Value2
    if(isValidASIN(ActiveCell)){
        asin = ActiveCell
    }else{
        let selectData = getCopySelection()
        if(isValidASIN(selectData)){
            asin = selectData
        }
    }


    if(!asin){
        alert('请选择一个包含asin的单元格')
    }else{
        let url = urls[select_site] + asin
        // 内置浏览器
        if(browser_type){
            let tsId = window.Application.PluginStorage.getItem("taskpane_id")
            if (!tsId) {
                let tskpane = window.Application.CreateTaskPane(url)
                let id = tskpane.ID
                window.Application.PluginStorage.setItem("taskpane_id", id)
                tskpane.Visible = true
            } else {
                let tskpane = window.Application.GetTaskPane(tsId)
                tskpane.Navigate(url)
                tskpane.Visible = true
            }
        }else{
            // 系统默认浏览器
            openBrowser(url)
        }
        
    }

    

}

export default {
    onOpenAmazon
}